package com.chap17.completablefuture;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <code>Demo16</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-10 14:58
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class Demo19 {
    public static void main(String[] args) {
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            int num = new Random().nextInt(10) + 1;
            sleep(num, TimeUnit.SECONDS);
            return "hello";
        });

        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            int num = new Random().nextInt(10) + 1;
            sleep(num, TimeUnit.SECONDS);
            return "world";
        });

        CompletableFuture<Object> result = CompletableFuture.anyOf(cf1, cf2);
        log.debug(""+result.join());
    }

    private static void sleep(int num, TimeUnit seconds) {
        try {
            seconds.sleep(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
